<?php
/**
 * 用户管理
 * Enter description here ...
 * @author cc
 *
 */
namespace Home\Controller;
use Think\Controller;
class UserController extends CommonController{
	public function way(){
		session("action","User");
		session("menu_id",I('get.menu_id'));
		$this->redirect("Public/index");
	}
	
	public function user(){
		$name = session('name');
		$user = M("sys_user");
		$data_user = $user->where("name='$name'")->find();
		$this->assign('data_user',$data_user);
		$this->display();
	}
	
	public function user_save(){
		$user_name = session('user_name');
		$user = M("sys_user");
		$data = array(
			'sex'=>$_POST['sex'],
			'birthday'=>$_POST['birthday'],
			'address'=>$_POST['address'],
			'home_add'=>$_POST['home_add'],
			'home_post'=>$_POST['home_post'],
			'home_tel'=>$_POST['home_tel'],
			'phone'=>$_POST['phone'],
			'email'=>$_POST['email'],
			'qq'=>$_POST['qq'],
			'msn'=>$_POST['msn']
		);
		$success = $user->where("user_name='$user_name'")->save($data);
		if($success){
	    	$this->systemlog('edit', '个人资料', "修改个人资料---".I('post.name'));
	    	$this->success("修改个人资料成功！","user");
	    }else {
	    	$this->error("修改个人资料失败！");
	    }
	}
	
	public function password(){
		$name = session('name');
		$this->assign('name',$name);
		$this->display();
	}
	
	public function password_save(){
		$user_name = session('user_name');
		$user = M("sys_user");
		$password1 = md5($_POST['password']);
		$password = $user->where("user_name='$user_name'")->getField('password');
		if($password == $password1){
			$data = array(
				'password'=>md5($_POST['new_password'])
			);
			$success = $user->where("user_name='$user_name'")->save($data);
			if($success){
		    	$this->systemlog('edit', '修改密码', "修改密码");
		    	$this->success("修改密码成功！","password");
		    }else {
		    	$this->error("修改密码失败！");
		    }
		}else{
			$this->error('旧密码输入错误，请重新修改！');
		}
	}
	
	public function index(){
		$this->display();
	}
	
	public function nav(){
		$dept = M("sys_dept");
		$data1 = $dept->where('dept_level=0')->order('dept_no asc')->select();//查询一级部门
		if(!empty($data1)){
			foreach ($data1 as $key1=>$value1){
				$dept_id1 = $value1['id'];
				$data2 = $dept->where('dept_level='.$dept_id1)->order('dept_no asc')->select();//查询二级部门
				if(!empty($data2)){
					foreach ($data2 as $key2=>$value2){
						$dept_id2 = $value2['id'];
						$data3 = $dept->where('dept_level='.$dept_id2)->order('dept_no asc')->select();//查询三级部门
						if(!empty($data3)){
							foreach ($data3 as $key3=>$value3){
								$dept_id3 = $value3['id'];
								$data4 = $dept->where('dept_level='.$dept_id3)->order('dept_no asc')->select();//查询四级部门
								if(!empty($data4)){
									foreach ($data4 as $key4=>$value4){
										$dept_id4 = $value4['id'];
										$data5 = $dept->where('dept_level='.$dept_id4)->order('dept_no asc')->select();//查询五级部门
										if(!empty($data5)){
											foreach ($data5 as $key5=>$value5){//如果级别很多的话，就继续写
//												$dept_id5 = $value5['id'];
//												$data6 = $dept->where('dept_level='.$dept_id5)->order('dept_no asc')->select();//查询六级部门
//												if(!empty($data6)){
//													
//												}
												$data[$key1]['one'][$key2]['two'][$key3]['three'][$key4]['four'][$key5]['dept_id'] = $value5['id'];
												$data[$key1]['one'][$key2]['two'][$key3]['three'][$key4]['four'][$key5]['dept_name'] = $value5['dept_name'];
											}
										}
										$data[$key1]['one'][$key2]['two'][$key3]['three'][$key4]['dept_id'] = $value4['id'];
										$data[$key1]['one'][$key2]['two'][$key3]['three'][$key4]['dept_name'] = $value4['dept_name'];
									}
								}
								$data[$key1]['one'][$key2]['two'][$key3]['dept_id'] = $value3['id'];
								$data[$key1]['one'][$key2]['two'][$key3]['dept_name'] = $value3['dept_name'];
							}
						}
						$data[$key1]['one'][$key2]['dept_id'] = $value2['id'];
						$data[$key1]['one'][$key2]['dept_name'] = $value2['dept_name'];
					}
				}
				$data[$key1]['dept_id'] = $value1['id'];
				$data[$key1]['dept_name'] = $value1['dept_name'];
			}
			
		}
		
		$this->assign('data',$data);
		$this->display();
	}
	
	public function lists(){
		$user = M("sys_user");
		$dept_id = I('get.dept_id');
		$error_log = M("login_error_log");
		$model = M();
		$count = $user->where('dept_id='.$dept_id)->count();
		$page = new \Think\Page($count,C("PAGE_LIST_ROWS"));
		$show = $page->show();
		$sql = "select user.*,dept.dept_name,priv.priv_name from oa_sys_user user,oa_sys_dept dept,oa_sys_priv priv where user.dept_id = dept.id and user.priv_id = priv.id and user.dept_id=$dept_id order by priv.priv_leve limit ".$page->firstRow.",".$page->listRows;
		$data = $model->query($sql);
		foreach($data as $key=>$value){
			$user_name = $value['user_name'];
			$count = $error_log->where("user_name = '$user_name'")->count();
			if($count>2){
				$data[$key]['user_status'] = "<a href='user_login_error_log?user_name=$user_name&dept_id=$dept_id' title='该账号登陆异常，系统自动锁定'>被禁用</a>";
			}else{
				$data[$key]['user_status'] = '正常';
			}
		}
		$this->assign('data',$data);
		$this->assign("dept_id",$dept_id);
		$this->assign("empty",emptyhtml("list"));
		$this->assign("page",$show);
		$this->display();
	}
	
	public function add(){
		$dept = M("sys_dept");
		$priv = M("sys_priv");
		
		$data_dept = $dept->select();
		$data_priv = $priv->select();
		
		$this->assign("data_dept", $data_dept);
		$this->assign("data_priv", $data_priv);
		
		$this->display();
	}
	
	public function insert(){
		if(!IS_POST){ $this->error("非法表单");exit;}
		$model = D("User");
		if( !$model->create() ){
			$this->error($model->getError());
		}else{
			$data = $_POST;
			$data["dept_aid_id"] = trim($data["dept_aid_id"],',');
			$data["priv_aid_id"] = trim($data["priv_aid_id"],',');
			$data['password'] = md5($data['password']);
			if( !empty($data["dept_aid_id"]) ) $data["dept_aid_id"] = implode(",", $data["dept_aid_id"]);
			if( !empty($data["priv_aid_id"]) ) $data["priv_aid_id"] = implode(",", $data["priv_aid_id"]);
			$success = $model->data($data)->add();
			if($success){
				$this->systemlog("add", "用户管理", "添加新用户---".$data['name']);
				$this->success("添加新用户成功！","lists?dept_id=".$data['dept_id']);
			}else{
				$this->error("添加新用户失败！");
			}
		}
	}
	
	public function edit(){
		$id = I('get.id');
		$dept_id = I('get.dept_id');
		if(!is_id($id)){ $this->error("非法参数"); }
		if(!is_id($dept_id)){ $this->error("非法参数"); }
		
		$dept = M("sys_dept");
		$priv = M("sys_priv");
		$user = M("sys_user");
		
		$data_dept = $dept->select();
		$data_priv = $priv->select();
		$data_user = $user->where("id=%d",$id)->find();
		if( !empty($data_user["dept_aid_id"]) ) $data_user["dept_aid_id"] = explode(",", $data_user["dept_aid_id"]);
		if( !empty($data_user["priv_aid_id"]) ) $data_user["priv_aid_id"] = explode(",", $data_user["priv_aid_id"]);
		
		$this->assign("data_dept", $data_dept);
		$this->assign("data_priv", $data_priv);
		$this->assign("data_user", $data_user);
		
		$this->display();
	}
	
	public function save(){
		if(!IS_POST){ $this->error("非法表单");exit;}
		$id = I('post.id');
		if(!is_id($id)){ $this->error("非法参数"); }
		
		$model = D("User");
		$data = I('post.');
		
		$data["dept_aid_id"] = trim($data["dept_aid_id"],',');
		$data["priv_aid_id"] = trim($data["priv_aid_id"],',');
		$data['password'] = md5($data['password']);
		if( !empty($data["dept_aid_id"]) ){
			$data["dept_aid_id"] = implode(",", $data["dept_aid_id"]);
		}else{
			$data["dept_aid_id"] = '';
		}
		if( !empty($data["priv_aid_id"]) ){
			$data["priv_aid_id"] = implode(",", $data["priv_aid_id"]);
		}else{
			$data["priv_aid_id"] = '';
		}
		if( !$model->create() ){
			$this->error($model->getError());
		}else{
			$success = $model->where("id=%d",$id)->data($data)->save();
			if($success){
				$this->systemlog("edit", "用户管理", "修改新用户---".$data['name']);
				$this->success("修改用户成功！","lists?dept_id=".$data['dept_id']);
			}else{
				$this->error("修改用户失败！");
			}
		}
	}
	
	public function delete(){
		$id = I('get.id');
		$dept_id = I('get.dept_id');
		if(!is_id($id)){ $this->error("非法参数"); }
		if(!is_id($dept_id)){ $this->error("非法参数"); }
		
		$model = M("sys_user");
		$name = $model->where("id=%d",$id)->getField("name");
		$success = $model->where("id=%d",$id)->delete();
		if($success){
			$this->systemlog("delete", "用户管理", "删除用户---".$name);
			$this->success("删除用户成功！","lists?dept_id=".$dept_id);
		}else{
			$this->error("删除用户失败！");
		}
	}

	public function user_login_error_log(){//账号登陆异常监测日志
		$user_name = I('get.user_name');
		$dept_id = I('get.dept_id');
		if( !is_user_name($user_name) ){ $this->error("非法参数！"); }
		if(!is_id($dept_id)){ $this->error("非法参数"); }
		
		$error_log = M("login_error_log");
		$data = $error_log->where("user_name='%s'", $user_name)->select();
		$this->assign('data',$data);
		$this->assign('user_name',$user_name);
		$this->assign('dept_id',$dept_id);
		$this->assign('empty',emptyhtml("list"));
		$this->display();
	}
	
	public function user_login_error_del(){//解除账号异常情况
		$user_name = I('post.user_name');
		$dept_id = I('post.dept_id');
		if( !is_user_name($user_name) ){ $this->error("非法参数！"); }
		if(!is_id($dept_id)){ $this->error("非法参数"); }
		
		$error_log = M("login_error_log");
		$success = $error_log->where("user_name='$user_name'")->delete();
		if($success){
			$this->success('解除封禁成功！','lists?dept_id='.$dept_id);
		}else{
			$this->error('解除封禁失败！');
		}
	}
	
	public function user_password_email(){//发送改密邮件到对方邮箱
		$time = date('Y-m-d H:i:s');
		$timestr = strtotime($time);
//		import('Vendor.phpmailer.phpmailer');
		Vendor('phpmailer.PHPMailer');
		$mail = new \PHPMailer();
		$id = I("get.id");
		if(!is_id($id)){ $this->error("非法参数"); }
		
		$user = M('sys_user');
		$data = $user->where('id=%d',$id)->find();
		if(empty($data['email'])){//如果对方的邮箱没有填写
			$this->ajaxReturn("对不起，对方没有填写接收邮件的邮箱！");
		}else{//发送一封改密的邮件到对方邮箱中
			$to_email = $data['email'];
			$to_username = $data['name'];
			$user_name = $data['user_name'];
			$mail->IsSMTP();//使用smtp方式发送
			$mail->Host = 'mail.sina.com';
			$mail->SMTPAuth = true;//smtp验证功能；
			$mail->Username = 'oa@sina.com';//smtp用户名
			$mail->Password = 'sina.com';//smtp密码
			$mail->From = 'oa@sina.com';//发件人
			$mail->FromName = "OA系统管理员";//发件人姓名
			$mail->AddAddress("$to_email", "$to_username");
			
			//获取随机数
			$rand_number = "";
			$str = array('0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
			for($i=0;$i<20;$i++){
				$rand_number .= $str[rand(0, count($str))];
			}
			$mail->IsHTML(true);
			$mail->CharSet = "utf-8";
			$url = C("PATH_URL")."/Login/reset_pass?t=$timestr&key=$rand_number&id=$id";
			$mail->Subject = "OA系统用户密码改密邮件";
			$content = "<body>";
			$content .= "OA系统用户  <font color='red' >$to_username</font> 你好：<br><br>OA系统管理员发送给您一封重置密码邮件，请 <a href=$url>点击这里</a> 按照页面提示修改密码！<br><br>";
			$content .= "该邮件在<font color='red' >2个小时</font>之内有效，请收到邮件后及时修改密码！<br><br>您也可以复制以下地址，在您新开的浏览器地址栏中粘贴。<br><br>$url";
			$content .= "</body>";
			$mail->Body = $content;
			$mail->AltBody = "这是一封修改OA系统用户名密码的邮件";
			
			if(!$mail->Send()){
				$this->ajaxReturn("改密邮件发送失败，错误原因：".$mail->ErrorInfo);
			}else{
				$user_mail = M("user_mail");
				$data_mail = array(
					'user_name' => $user_name,
					'send_time' => $time,
					'status' => 0,
					'tpl' => 1,
					'rand_number' => $rand_number
				);
				$user_mail->add($data_mail);
				$this->ajaxReturn("改密邮件发送成功！");
			}
		}
	}
	
	public function tongbu(){//同步考勤机人员信息与OA系统用户信息
		$user_bak = M("sys_user_bak");
		$data_user_bak = $user_bak->select();
		foreach ($data_user_bak as $key=>$value){
			$user_id[$key]=$value['user_id'];
		}
		
		$conn = new com("ADODB.Connection"); 
		$connstr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".realpath(C("ACCESS_PATH")."att2000.mdb"); 
		$conn->Open($connstr);
		$sql = "select * from USERINFO";
		$res=new com("adodb.recordset");                    //用com类声明一个记录集对象
		$res->open($sql,$conn,1,1);   
		if($res->EOF || $res->BOF){
			$this->ajaxReturn("值为空！");
		}else{
			$i=0;
			while (!$res->EOF){
				if(!in_array($res->Fields('USERID')->value,$user_id)){
					$user_id = $res->Fields('USERID')->value;
					$name = iconv('gbk','utf-8',$res->Fields('Name')->value);
					$data = array(
						'user_id'=>$user_id,
						'name'=>$name
					);
					$success = $user_bak->add($data);
					if(!$success){
						$this->error('用户编号为：'.$user_id.'的用户更新失败，信息同步终止！');
					}
					$i++;
					$this->log(session('name'), '同步', '用户管理', '同步用户--'.$name.'信息');
				}
				$res->movenext; 
			}
			$this->ajaxReturn("信息同步成功，本次共同步了 ".$i." 条数据");
		}
	}
	
	public function select_user(){//查看用户编号
		$user_bak = M("sys_user_bak");
		$name = I("get.name");
		if( !is_name($name) ){ $this->error("姓名只能是汉字！"); }
		$data_user_bak = $user_bak->where("name='%s'",$name)->select();
		$this->assign("data",$data_user_bak);
		$this->assign("empty","<tr><td colspan=2>你输入的用户不存在，请同步用户信息，或者联系考勤机管理员！</td></tr>");
		$this->display();
	}
	
	public function check_user_name(){
		$user = M("sys_user");
		$user_name = I('get.user_name');
		$count = $user->where("user_name='$user_name'")->count();
		if($count > 0){
			$this->ajaxReturn("<font color='red'>该用户名已被注册!</font>");
		}else{
			$this->ajaxReturn("<font color='greed'>该用户名可以注册!</font>");
		}
	}
	
	public function photo(){
		$this->assign("user_name", session("user_name"));
		$this->display();
	}
	
	public function upfile(){
		$path = C("PUBLIC_PATH")."avatar";
		$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path;
		if(!is_dir($targetPath)){
			mkdir($targetPath,'0777',recursive);
		}

		$savePath = $targetPath.'/';  //图片存储路径
		$savePicName = session("user_name");  //图片存储名称
		$filename48 = $savePath.$savePicName.".jpg"; 
		$pic2=base64_decode($_POST['pic2']);  
		file_put_contents($filename48,$pic2);
		$rs['status'] = 1;
		print json_encode($rs);
	}
    
    public function _empty($name){
    	$this->emptyaction($name);
    }
}
?>